<?php

class user extends cms_controller {

    function __construct() {
        parent::__construct();
        $this->load->model('user_model', 'user');
        $this->load->library('email_system');
    }

    function index() {
        redirect(__CLASS__ . '/profile');
    }

    // start function login 
    public function login() {

        $this->pass['head_title'] = lang('label_title_login');
        $back_url = $this->session->userdata('back_page');
        if ($back_url == __CLASS__ . '/logout' || $back_url == __CLASS__ . '/login' || preg_match('/admin/', $back_url)) {
            $back_url = '';
        } elseif ($back_url == 'cart/checkout') {
            $back_url = 'cart';
        }

        $validation = array(
            array(
                'field' => 'username',
                'label' => lang('label_email'),
                'rules' => 'required'
            ),
            array(
                'field' => 'password',
                'label' => lang('label_password'),
                'rules' => 'required|min_length[6]'
            )
        );

        $this->form_validation->set_rules($validation);
        if ($this->form_validation->run() == FALSE) {
            $this->themes->render(__CLASS__ . '/login', $this->pass);
        } else {
            $this->user_data = $this->user->login($this->input->post('username'), $this->input->post('password'));
            if ($this->user_data == false) {
                $this->themes->set_message(array('url' => 'user/login', 'type' => 'error', 'message' => 'message_login_faild'));
            } else {
                $this->login_done('user', $back_url);
            }
        }
    }

// end function login 
    // start function logout

    function register() {
        if ($this->input->post()) {
            $this->session->set_userdata('post', $this->input->post());
            if ($this->input->post('privacy')) {
                $this->load->library('form_validation');
                $this->form_validation->set_rules('username', lang('label_username'), 'trim|required|is_unique[user.username]|min_length[4]');
                $this->form_validation->set_rules('email', lang('label_email'), 'trim|required|is_unique[user.email]|valid_email');
                $this->form_validation->set_rules('confemail', lang('label_confemail'), 'trim|required|is_unique[user.email]|valid_email|matches[email]');
                $this->form_validation->set_rules('password', lang('label_password'), 'trim|required|min_length[4]');
                $this->form_validation->set_rules('confpassword', lang('label_confpassword'), 'trim|required|min_length[4]|matches[password]');
                if ($this->form_validation->run()) {
                    if ($this->input->post('subscrib'))
                        $subscrib = 'YES';
                    else
                        $subscrib = 'NO';


                    $code = substr(md5(time()), -10, 10);

                    $save['username'] = $this->input->post('username');
                    $save['email'] = $this->input->post('email');
                    $save['password'] = md5($this->input->post('password'));
                    $save['confirm_code'] = $code;
                    $save['subscrib'] = $subscrib;
                    $save['confirm_email'] = 'NO';
                    $save['mode'] = 'user';
                    if ($this->user->save($save)) {
                        $to = $save['email'];
                        $subject = lang('message_activation_subject');
                        $msg = str_replace('%s', $code, lang('message_activation_body'));
                        $headers = 'From: ' . get_option('site_email');
                        $this->load->library('email_system');
                        $this->email_system->SendEmail($to, $subject, false, false, false, $msg);
                        $this->session->unset_userdata('post');
                        $this->themes->set_message(array('type' => 'success', 'url' => __CLASS__ . '/login', 'message' => 'message_register_success'));
                    } else {
                        get_save_error();
                    }
                } else {
                    get_validation_errors();
                }
            } else {
                $this->themes->set_message(array('type' => 'error', 'url' => current_url(), 'message' => 'message_accept_privacy'));
            }
        } else {
            if ($this->session->userdata('post'))
                $this->pass['post'] = $this->session->userdata('post');
            $this->load->model('pages_model', 'pages');
            $this->pass['page'] = $this->pages->is_found(array('slug' => 'privacy'), array(), 'row');
            $this->themes->render('user/register', $this->pass);
        }
    }

    public function password_check($str) {

        $sql = $this->db->get_where('users', array('id' => $this->user_id, 'password' => md5($str)));

        if (!$sql->num_rows()) {
            $this->form_validation->set_message('password_check', '%s Not Correct');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    public function email_check($str) {

        $sql = $this->db->get_where('users', array('id !=' => $this->user_id, 'email' => $str));

        if ($sql->num_rows()) {
            $this->form_validation->set_message('email_check', '%s Not Correct');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    // start function login 
    public function profile() {
        if ($id = $this->session->userdata('user_ID')) {
            $this->pass['user'] = $this->user->is_found(array('id' => $id), array(), 'row', __CLASS__ . '/logout');
            $this->themes->render('user/profile', $this->pass);
        }
        else
            redirect($this->agent->refrrer());
    }

    public function edit() {
        if ($id = $this->session->userdata('user_ID')) {
            $this->pass['user'] = $data = $this->user->is_found(array('id' => $id), array(), 'row', __CLASS__ . '/logout');

            if ($this->input->post()) {
                $this->session->set_userdata('post', $this->input->post());
                $this->load->library('form_validation');

                $this->form_validation->set_rules('fname', lang('label_fname'), 'required');
                $this->form_validation->set_rules('gender', lang('label_gender'), 'required|callback_gender_check');
                $this->form_validation->set_rules('day', lang('label_birthday'), 'required|is_natural_no_zero');
                $this->form_validation->set_rules('month', lang('label_birthday'), 'required|is_natural_no_zero');
                $this->form_validation->set_rules('year', lang('label_birthday'), 'required|is_natural_no_zero');
                $this->form_validation->set_rules('city', lang('label_city'), 'required|is_natural_no_zero');
                $this->form_validation->set_rules('mobile', lang('label_mobile'), 'required|is_natural');
                if ($data->email != $this->input->post('email'))
                    $this->form_validation->set_rules('email', lang('label_email'), 'trim|required|is_unique[user.email]|valid_email');
                if ($this->input->post('password')) {
                    $this->form_validation->set_rules('oldpassword', lang('label_old_password'), 'trim|required|callback_oldpass_check');
                    $this->form_validation->set_rules('password', lang('label_password'), 'trim|required|min_length[4]');
                    $this->form_validation->set_rules('confpassword', lang('label_confpassword'), 'trim|required|min_length[4]|matches[password]');
                }

                if ($this->form_validation->run()) {

                    if ($this->input->post('subscrib'))
                        $subscrib = 'YES';
                    else
                        $subscrib = 'NO';
                    $save['first_name'] = $this->input->post('fname');
                    $save['middle_name'] = $this->input->post('mname');
                    $save['last_name'] = $this->input->post('lname');
                    $save['gender'] = strtoupper(substr($this->input->post('gender'), 0, 2));
                    $save['day'] = $this->input->post('day');
                    $save['month'] = $this->input->post('month');
                    $save['year'] = $this->input->post('year');
                    $save['city_id'] = $this->input->post('city');
                    $save['mobile'] = $this->input->post('mobile');
                    if ($data->email != $this->input->post('email')) {
                        $save['email'] = $this->input->post('email');
                        $code = substr(md5(time()), -10, 10);
                        $save['confirm_code'] = $code;
                        $save['confirm_email'] = 'NO';
                    }
                    $save['subscrib'] = $subscrib;
                    if ($this->input->post('password'))
                        $save['password'] = md5($this->input->post('password'));

                    if ($this->user->save($save, array('id' => $id), TRUE)) {
                        $this->session->unset_userdata('post');
                        if (isset($code)) {
                            $to = $this->input->post('email');
                            $subject = lang('message_activation_subject');
                            $msg = str_replace('%s', $code, lang('message_activation_body'));
                            $headers = 'From: ' . get_option('site_email');
                            $this->email_system->SendEmail($to, $subject, false, false, false, $msg);
                            $this->themes->set_message(array('type' => 'success', 'url' => __CLASS__ . '/profile', 'message' => 'message_register_success'));
                        } else {
                            $this->themes->set_message(array('type' => 'success', 'url' => __CLASS__ . '/profile', 'message' => 'message_save_success'));
                        }
                    } else {
                        get_save_error();
                    }
                } else {
                    get_validation_errors();
                }
            }

            $this->load->model('cities_model', 'cities');
            $this->pass['cities'] = $this->cities->get();

            $this->themes->render('user/editprofile', $this->pass);
        }
        else
            redirect($this->agent->refrrer());
    }

    public function gender_check($str) {
        if (in_array($str, array('male', 'female')))
            return true;
        else {
            $this->form_validation->set_message('gender_check', lang('message_wrong_data'));
            return FALSE;
        }
    }

    public function oldpass_check($str) {
        $data = $this->pass['user'];
        if (md5($str) == $data->password)
            return true;
        else {
            $this->form_validation->set_message('oldpass_check', lang('message_wrong_data'));
            return FALSE;
        }
    }

    // start function logout
    public function logout() {
        $this->destroy_session('user');
    }

    function resend() {
        if ($this->user_id) {
            $user = $this->user->is_found(array('id' => $this->user_id), array(), 'row', __CLASS__ . '/logout');
            $code = substr(md5(time()), -10, 10);
            $save['confirm_code'] = $code;
            $save['confirm_email'] = 'NO';
            $this->user->save($save, array('id' => $this->user_id), TRUE);
            $to = $user->email;
            $subject = lang('message_activation_subject');
            $msg = str_replace('%s', $code, lang('message_activation_body'));
            $headers = 'From: ' . get_option('site_email');
            $this->email_system->SendEmail($to, $subject, false, false, false, $msg);
            $this->themes->set_message(array('type' => 'success', 'url' => __CLASS__ . '/profile', 'message' => 'message_resend_success'));
        }
        redirect($this->agent->referrer());
    }

    // forget password
    public function forgetpassword() {

        $data['head_title'] = lang('label_forgetpassword');
        $back_url = $this->session->userdata('back_page');
        if ($back_url == 'user/logout' || strpos('admin', $back_url) !== false) {
            $back_url = '';
        }

        if ($this->input->post()) {
            $validation = array(
                array(
                    'field' => 'email',
                    'label' => lang('label_email'),
                    'rules' => 'required|valid_email|is_found[user.email]'
                )
            );

            $this->form_validation->set_rules($validation);
            if ($this->form_validation->run()) {
                $email = $this->input->post('email');
                $code = substr(md5(time()), -10, 10);
                if ($data = $this->user->is_found(array('email' => $email))) {
                    $to = $this->input->post('email');
                    $subject = lang('message_reset_subject');
                    $message = str_replace('%s', $code, lang('message_reset_body'));
                    $headers = 'From: ' . get_option('site_email');
                    $this->user->save(array('confirm_code' => $code), array('id' => $data->id), TRUE);
                    $this->load->library('email_system');
                    $this->email_system->SendEmail($to, $subject, false, false, false, $message);
                    $this->themes->set_message(array('url' => '', 'type' => 'success', 'message' => "message_send_forget"));
                }
            } else {
                get_validation_errors();
            }
        }
        $this->themes->render('user/forget');
    }

    // reset password
    public function reset_password($code = FALSE) {
        $this->pass['user'] = $this->user->is_found(array('confirm_code' => $code));

        if (!$code) {
            redirect();
        }
        if ($this->input->post()) {

            $this->form_validation->set_rules('email', lang('label_email'), 'trim|required|valid_email|is_found[user.email]');
            $this->form_validation->set_rules('code', lang('label_forgetcode'), 'trim|required|is_found[user.confirm_code]');
            $this->form_validation->set_rules('password', lang('label_password'), 'trim|required|min_length[6]');
            $this->form_validation->set_rules('confpassword', lang('label_confpassword'), 'trim|required|min_length[6]|matches[password]');

            if ($this->form_validation->run()) {
                $email = $this->input->post('email');
                $code = $this->input->post('code');
                $password = $this->input->post('password');
                if ($data = $this->user->is_found(array('email' => $email, 'confirm_code' => $code))) {
                    $this->user->save(array('confirm_code' => '', 'password' => md5($password)), array('id' => $data->id), TRUE);
                    redirect('user/login');
                }
            } else {
                get_validation_errors();
            }
        }
        $this->themes->render('user/reset', $this->pass);
    }

    public function activation($code = FALSE) {
        if ($code) {
            $user = $this->user->is_found(array('confirm_code' => $code), array(), 'row', __CLASS__ . '/login');
            $save['confirm_code'] = '';
            $save['confirm_email'] = 'YES';
            $save['active'] = 'YES';
            if ($this->user->save($save, array('id' => $user->id), TRUE)) {
                if ($user->subscrib == 'YES') {
                    $this->load->model('maillinglist_model', 'mlist');
                    $d = $this->mlist->get(array('email' => $user->email), FALSE, 'row');
                    if (!count($d) > 0) {
                        $mlist['email'] = $user->email;
                        $mlist['active'] = 'YES';
                        $this->mlist->save($mlist);
                    }
                }
                $this->user_data = $this->user->get(array('id' => $user->id), array(), 'row');
                $this->login_done('user', __CLASS__ . '/profile', 'message_activation_success');
            } else {
                $this->themes->set_message(array('type' => 'error', 'url' => __CLASS__ . '/login', 'message' => 'message_wrong_activation'));
            }
        } else {
            show_404();
        }
    }

    function stores() {
        $stores = FALSE;
        $stores = get_favorite_stores();
        $this->pass['stores'] = $stores;
        $this->themes->render('user/stores', $this->pass);
    }

    function purshases() {
        $this->load->model('seller_items_model', 'dealsmo');
        $this->pass['data'] = $this->dealsmo->get(array('type' => 'SEND', 'user_id' => $this->user_id));
        $this->themes->render('user/purshases', $this->pass);
    }

    function showdeal($id = false, $any = FALSE, $ty = FALSE) {
        if (is_numeric($id)) {
            $this->load->model('invoicie_items_model');
            $this->pass['details'] = $details = $this->invoicie_items_model->get(array('id' => $id), FALSE, 'row');
            $this->load->model('seller_items_model', 'dealsmo');
            $this->pass['data'] = $data = $this->dealsmo->get(array('item_id' => $id), FALSE, 'row');
            if (count($details) <= 0) {
                redirect($this->agent->referrer());
            }
            if ($ty)
                $this->pass['sales'] = TRUE;
            $this->themes->render('user/showdeal', $this->pass);
        } else {
            redirect($this->agent->referrer());
        }
    }

    function shipingdetails($id = FALSE, $any = FALSE, $ty = FALSE) {
        if (is_numeric($id)) {
            $this->load->model('seller_items_model', 'dealsmo');
            $data = $this->dealsmo->is_found(array('id' => $id), array(), 'row', $this->agent->referrer());
            $this->load->model('items_sent_model', 'itemsent');
            $shipingdetails = $this->itemsent->get(array('seller_items_id' => $id), false, 'row');
            $this->load->model('invoicie_items_model');
            $this->pass['details'] = $this->invoicie_items_model->get(array('id' => $data->item_id), FALSE, 'row');
            if (count($shipingdetails) > 0) {
                $this->pass['shipingdetails'] = $shipingdetails;
                if ($ty)
                    $this->pass['sales'] = TRUE;
                $this->themes->render('user/showshiping', $this->pass);
                return;
            }
        }
        show_404();
    }

    function sales() {
        $this->load->model('store_model', 'stores');
        $this->pass['store'] = $store = $this->stores->is_found(array('owner_id' => $this->user_id), array(), 'row', 'store/create/1', 'message_create_yourstore');
        $this->load->model('seller_items_model', 'dealsmo');
        $this->pass['data'] = $this->dealsmo->get(array('type' => 'SEND', 'seller_id' => $store->id));
        $this->themes->render('user/sales', $this->pass);
    }

    function delivers($id = false, $inv = false) {
        if (is_numeric($id)) {
            $this->load->model('seller_items_model', 'dealsmo');
            $this->load->model('store_model', 'stores');
            $this->load->model('invoicie_items_model');
            $data = $this->dealsmo->is_found(array('id' => $id), array(), 'row', $this->agent->referrer());
            $store = $this->stores->is_found(array('id' => $data->seller_id), array(), 'row', $this->agent->referrer());
            $details = $this->invoicie_items_model->is_found(array('id' => $data->item_id), array(), 'row', $this->agent->referrer());
            $save['user_accept'] = 'YES';
            $this->dealsmo->save($save, array('id' => $id), true);
            $this->load->model('wallet_model');
            $save = NULL;
            $save['user_id'] = $store->owner_id;
            $save['operation'] = 'plus';
            $save['amount'] = $details->total_price + $details->shiping - $details->discount;
            $save['note'] = lang('label_buy_product');
            $save['status'] = 'active';
            $save['type'] = 'buy';
            $this->wallet_model->save($save);
            $this->themes->set_message(array('type' => 'success', 'url' => $this->agent->referrer(), 'message' => 'message_save_success'));
            return;
        }
        redirect($this->agent->referrer());
    }

}